package cn.wangxl.vertx.starter.web;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.ext.web.Router;

/**
 * 重新路由:
 * 可以用于适当情况下的重路由：
 *  查询用户为空，返回404
 *
 */
public class SubRouteVerticle extends AbstractVerticle {

  @Override
  public void start(Future<Void> startFuture) throws Exception {
    Vertx vertx = Vertx.vertx();
    HttpServer server = vertx.createHttpServer();

    Router mainRouter = Router.router(vertx);
    mainRouter.route("/user").handler(ctx->{
      System.out.println("设备主路由");
      ctx.response().end();
    });

    Router subRouter = Router.router(vertx);
    subRouter.get("/info").handler(ctx->{
      System.out.println("子路由--查询设备");
      ctx.response().end();
    });
    subRouter.put("/info").handler(ctx->{
      System.out.println("子路由--修改设备");
      ctx.response().end();
    });
    subRouter.delete("/info").handler(ctx->{
      System.out.println("子路由--删除设备");
      ctx.response().end();
    });

    Router subRouter1 = Router.router(vertx);

    subRouter1.get("/info").handler(ctx->{

      System.out.println("查询订单");

      ctx.response().end();
    });

    subRouter1.put("/info").handler(ctx->{

      System.out.println("修改订单");

      ctx.response().end();
    });

    mainRouter.mountSubRouter("/device",subRouter);

    mainRouter.mountSubRouter("/order",subRouter1);

    // .requestHandler() 最后一个才能生效
    server.requestHandler(mainRouter).listen(9999, http -> {
      if (http.succeeded()) {
        startFuture.complete();
        System.out.println("HTTP server started on port 8888");
      } else {
        startFuture.fail(http.cause());
      }
    });
  }


  public static void main(String[] args) throws Exception {
    new SubRouteVerticle().start(Future.future());
  }
}
